package com.jdym.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class JavaMailMessage {
    /**
     *
     * @param name   收件人姓名
     * @param mail   收件人email
     * @param firmId   激活账号id
     * @throws Exception
     */
    public static void sendMessage(String name,String mail,int firmId) throws Exception {
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);
        msg.setSubject("您的 商城 帐户－请确认您的电子邮件地址");
        StringBuilder builder = new StringBuilder();
        builder.append("尊敬的用户 "+name+":");
        builder.append("<br/>请验证您的电子邮件地址以完成 商城 帐户创建。");
        builder.append("<br/>验证邮箱地址" + "<a href='http://127.0.0.1:8010/activeEmail?firmId="+firmId+"'>验证邮箱地址</a>");
        builder.append("<br/><br/><span style='font-size:10px;'>我们收到了使用您的电子邮件地址申请 商城 帐户的请求。如果您没有发出请求，请忽略这封邮件。</span>");
        builder.append("<br/>谢谢 " );
        builder.append("<br/>商城客服 " );
        msg.setText(builder.toString());
        msg.setFrom(new InternetAddress("859418490@qq.com"));//**发送人的邮箱地址**

        // 设置发送时间
        msg.setSentDate(new Date());

        // 设置 E-mail 正文部分
//      msg.setText(body);
        msg.setContent(builder.toString(), "text/html;charset = gbk");

        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", "859418490@qq.com", "tgfexvymxmabbejh");//**发送人的邮箱地址**
        // 找到jre/lib/security/java.security  去掉 SSLv3, TLSv1, TLSv1.1
        transport.sendMessage(msg, new Address[] { new InternetAddress(mail) });//**接收人的邮箱地址**

        transport.close();
    }
}
